package bzapps.weynak;

import java.util.ArrayList;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

public class PhotoOverlay extends ItemizedOverlay<OverlayItem>
{
	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
	private Context mContext;
	String snap_url;
	ProgressBar pb;
	ImageView img;
	Bitmap m;
	Drawable photo;

 public PhotoOverlay(Drawable defaultMarker, Context context, String snap)
 {
	 super(boundCenter(defaultMarker));
	 mContext = context;
	 snap_url = snap;
 }

 @Override
 public void draw(Canvas canvas, MapView mapView, boolean shadow) {
 	// TODO Auto-generated method stub
 	super.draw(canvas, mapView, false);
 }
 
 public void addOverlay(OverlayItem overlay)
 {
	 mOverlays.add(overlay);
	 populate();
 }
 @Override
 protected OverlayItem createItem(int i)
 {
	 return mOverlays.get(i);
 }
 @Override
 public int size()
 {
	 return mOverlays.size();
 }
 @Override
 protected boolean onTap(int index)
 {
	 
	 Dialog mydialog = new Dialog(mContext);
	 mydialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	 mydialog.setContentView(R.layout.photo_layout);
	 OverlayItem item = mOverlays.get(index);
	 img = (ImageView)mydialog.findViewById(R.id.photo_snap);
	 TextView client = (TextView)mydialog.findViewById(R.id.photo_layout_clientid);
	 TextView date = (TextView)mydialog.findViewById(R.id.photo_layout_date);
	 pb = (ProgressBar)mydialog.findViewById(R.id.progressBar1);
	 client.setText(item.getTitle());
	 date.setText(item.getSnippet());
	 pb.setVisibility(View.VISIBLE);
	 final String url = "http://www.bz-apps.com/weynak/uploadedimages/"+snap_url+".jpg";
	 mydialog.show();
	 loadImage(url);

	return true;
 }
	public Handler pic = new Handler(){
		
		@Override
		public void handleMessage(Message msg){
				switch(msg.what){
				
				case 0:
					if(m!=null){
						 img.setImageBitmap(m);
						 pb.setVisibility(View.GONE);
					 }
				break;
				case 1:
					img.setImageDrawable(photo);
					pb.setVisibility(View.GONE);
				break;
					
			}
		  }
	};
	
	public void loadImage(final String url){
		
		 new Thread(){
			 @Override
			public void run(){
				 photo = WeynakUtils.getToCache(mContext, snap_url);
				 if(photo != null){
					 pic.sendEmptyMessage(1);
				 }
				 else{
					 m = WeynakUtils.getImageBitmap(url);
					 WeynakUtils.storeToCache(mContext, snap_url, m);
					 pic.sendEmptyMessage(0); 
				 }
			 }
		 }.start();
	}
}